//
//  CYTabBar.swift
//  CYWeiBo
//
//  Created by Mac on 16/7/10.
//  Copyright © 2016年 Mac. All rights reserved.
//

import UIKit

//  1.定义协议必须继承NSObjectProtocol, 才能用weak关键对属性进行弱引用
protocol CYTabBarDelegate: NSObjectProtocol {
    func didSelectedComposeButton()
}

class CYTabBar: UITabBar {
    //  点击点击撰写按钮的闭包
    var composeButtonClosure: (()->())?
    //  2.定义代理对象
    weak var cyDelegate: CYTabBarDelegate?
    
    //  懒加载创建button
    private lazy var composeButton: UIButton = {
        let button = UIButton()
        // 添加点击事件
        button.addTarget(self, action: "composeButtonAction", forControlEvents: .TouchUpInside)
        
        //  设置图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Highlighted)
        
        //  设置背景图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted)
        
        //让button 和图片大小一样
        button.sizeToFit()
        
        return button
    }()
    
    //  重写父类的init方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        //  添加
        addSubview(composeButton)
    }

    //  加载XIB或者storyboard才会调用
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: -- 点击事件
    @objc private func composeButtonAction() {
        print("哈哈哈")
        
        // 执行闭包
        composeButtonClosure?()
        
        //  3.使用代理对象调用
        cyDelegate?.didSelectedComposeButton()
    }
    
    
    override func layoutSubviews() {
        super.layoutSubviews()
        //  设置撰写按钮的中心点
        composeButton.centerX = width * 0.5
        composeButton.centerY = heigt * 0.5

        //   获取系统控件
        //  计算控件的宽度
        let itemWith = width / 5
        //  记录遍历的是第几个按钮
        var index = 0
        for value in subviews {
            if value.isKindOfClass(NSClassFromString("UITabBarButton")!){
            
                value.x = CGFloat(index) * itemWith
                
                value.width = itemWith
                
                if index == 1 {
                    index++
                }
                
                index++
            }
        }

    }
    
    
}

